package com.jucai.pppeiyouclient.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.bean.FindOrderDetailsBean;
import com.jucai.pppeiyouclient.bean.UserGoldBean;
import com.jucai.pppeiyouclient.bean.WechatPay;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.DateUtil;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.PayResult;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.view.dialog.PlayOrderYueDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import static com.jucai.pppeiyouclient.view.activity.LoginActivity.activity;

/**
 * 发现支付页
 * Created by chenjidong on 2017/5/13.
 */

public class FindPayOrderActivity extends BaseActivity implements CompoundButton.OnCheckedChangeListener {

    private static final int SDK_PAY_FLAG = 1;
    private static final int YINLIAN_PLAY_TN = 2;

    private String goods_id, sellerid, cateid, find_type;
    private int type;//0 商品, 1 酒店订单

    private ImageView ivCommodity, iv_subtract, iv_add;
    private TextView tv_count, tv_number;

    private TextView tvCommodityTitle, tvCommoditySubhead, tvCommodityPrice;


    private EditText et_name, et_phone, et_remark;
    private LinearLayout llt_hotel_hint;


    private TextView tv_selector_title, tv_selector_count;
    private ImageView iv_selector_subtract, iv_selector_add;

    private TextView tv_price, tv_privilege, applyPay_surePayTv;

    private CheckBox weixinCb;
    private CheckBox zhifubaoCb;
    private CheckBox yinlianCb;
    private CheckBox yueCb;

    private TextView tv_hotel_date;

    FindOrderDetailsBean bean;
    FindOrderDetailsBean.DataBean commodityBean;
    UserGoldBean userGoldBean;
    private int count = 1;
    private int total = 0;
    private double dPrice = 0;
    private int dCoin = 0;
    private int coinCount = 0;
    private ProgressDialog progressBar;
    private static String jumpUrl;
    private double currentPrice, strPrice;
    private String startDate, endDate;
    private int hotelTimeCount;//住多少天
    private int tUseCoin = 0;
    private TextView tv_hotel_hint;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);

    private PlayOrderYueDialog playOrderDialog = null;

    private static Activity self;
    public static void payWxDone() {
        if (self != null && self instanceof FindPayOrderActivity) {
            Intent intent = new Intent();
            intent.putExtra("jumpUrl", jumpUrl);
            self.setResult(Activity.RESULT_OK, intent);
            self.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (self != null)
            self = null;
        if (!TextUtils.isEmpty(jumpUrl)){
            jumpUrl = null;
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        self = this;
        setContentView(R.layout.activity_find_pay_order);

        iv_subtract = (ImageView) findViewById(R.id.iv_subtract);
        iv_add = (ImageView) findViewById(R.id.iv_add);
        ivCommodity = (ImageView) findViewById(R.id.iv_logo);

        tv_count = (TextView) findViewById(R.id.tv_count);
        tv_number = (TextView) findViewById(R.id.tv_number);
        tvCommodityTitle = (TextView) findViewById(R.id.tv_title);
        tvCommoditySubhead = (TextView) findViewById(R.id.tv_subhead);
        tvCommodityPrice = (TextView) findViewById(R.id.tv_commodity_price);


        et_name = (EditText) findViewById(R.id.et_name);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_remark = (EditText) findViewById(R.id.et_remark);

        llt_hotel_hint = (LinearLayout) findViewById(R.id.llt_hotel_hint);

        tv_selector_title = (TextView) findViewById(R.id.tv_selector_title);
        tv_selector_count = (TextView) findViewById(R.id.tv_selector_count);

        iv_selector_add = (ImageView) findViewById(R.id.iv_selector_add);
        iv_selector_subtract = (ImageView) findViewById(R.id.iv_selector_subtract);

        weixinCb = (CheckBox) findViewById(R.id.applyPay_weixinCb);
        zhifubaoCb = (CheckBox) findViewById(R.id.applyPay_zhifubaoCb);
        yinlianCb = (CheckBox) findViewById(R.id.applyPay_yinlianCb);
        yueCb = (CheckBox) findViewById(R.id.applyPay_yueCb);

        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_privilege = (TextView) findViewById(R.id.tv_privilege);
        applyPay_surePayTv = (TextView) findViewById(R.id.applyPay_surePayTv);

        tv_hotel_date = (TextView) findViewById(R.id.tv_hotel_date);
        tv_hotel_hint = (TextView) findViewById(R.id.tv_hotel_hint);

        playOrderDialog = new PlayOrderYueDialog(this);
    }

    @Override
    protected void initData() throws ParseException {


        type = getIntent().getIntExtra("type", 0);
        goods_id = getIntent().getStringExtra("goods_id");
        sellerid = getIntent().getStringExtra("sellerid");
        cateid = getIntent().getStringExtra("cateid");
        find_type = getIntent().getStringExtra("find_type");
        startDate = getIntent().getStringExtra("startDate");
        endDate = getIntent().getStringExtra("endDate");

        if (TextUtils.equals(find_type, "goods")) {
            llt_hotel_hint.setVisibility(View.GONE);
            tv_number.setText("数量");

        } else {
            llt_hotel_hint.setVisibility(View.GONE);//暂时隐藏
            tv_number.setText("房间数");
            if (!TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(endDate)) {
                hotelTimeCount = DateUtil.getBetweenDayNumber(DateUtil.parseDate(startDate), DateUtil.parseDate(endDate));

                tv_hotel_date.setText(startDate + " 入住 ——" + endDate + " 离店 共" + hotelTimeCount + "晚");
                tv_hotel_date.setVisibility(View.VISIBLE);
            }
        }
        tv_privilege.setText("");
        getCommodityData();
        getGoldData();
    }

    private void getCommodityData() {
        Map<String, String> mapRegister = new HashMap<>();
        mapRegister.put("service", "Find_Order.buy");
        mapRegister.put("goods_id", goods_id);
        mapRegister.put("member_id", LoginUtils.getMember_id(this));
        mapRegister.put("token", LoginUtils.getToken(this));

        CommonRequestNetData.getJsonString(this, false, mapRegister, new CommonRequestNetData.JsonStringCallBack() {
            Gson gson;

            @Override
            public void parseJsonString(String str) {
                try {
                    if (gson == null)
                        gson = new Gson();
                    bean = gson.fromJson("{data:" + str + "}", FindOrderDetailsBean.class);
                    setData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getGoldData() {
        Map<String, String> mapRegister = new HashMap<>();
        mapRegister.put("service", "Client_Wallet.getBalance");
        mapRegister.put("token", LoginUtils.getToken(this));
        mapRegister.put("member_id", LoginUtils.getMember_id(this));

        CommonRequestNetData.getJsonString(this, false, mapRegister, new CommonRequestNetData.JsonStringCallBack() {
            Gson gson;

            @Override
            public void parseJsonString(String str) {
                if (gson == null)
                    gson = new Gson();
                userGoldBean = gson.fromJson(str, UserGoldBean.class);
                setGoldData();

            }
        });
    }

    private void updateCoin() {
        tv_selector_count.setText(coinCount + "");
        updatePrice();
    }


    private void setGoldData() {
        try {
            if (userGoldBean != null && !TextUtils.isEmpty(userGoldBean.getMember_coin())) {
                if (TextUtils.isDigitsOnly(userGoldBean.getMember_coin())) {
                    dCoin = Integer.parseInt(userGoldBean.getMember_coin());
                    tv_selector_title.setText("使用金币抵扣，请输入抵扣金币（总额：" + dCoin + "）");
                } else
                    tv_selector_title.setText("使用金币抵扣，请输入抵扣金币（总额：" + dCoin + "）");
            } else
                tv_selector_title.setText("使用金币抵扣，请输入抵扣金币（总额：" + dCoin + "）");
            updateCoin();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setData() {
        if (bean != null) {
            tvCommodityTitle.setText(bean.getData().getGoods_info().getGoodname());
            tvCommodityPrice.setText("¥" + bean.getData().getGoods_info().getGoodmoney());
            tvCommoditySubhead.setText(bean.getData().getGoods_info().getGoods_option());

            if (bean.getData().getGoods_info().getGoodsimg() != null && bean.getData().getGoods_info().getGoodsimg().size() > 0)
                Glide.with(this).load(bean.getData().getGoods_info().getGoodsimg().get(0)).into(ivCommodity);

            if (!TextUtils.isEmpty(bean.getData().getGoods_info().getGoodmoney())) {
                dPrice = Double.parseDouble(bean.getData().getGoods_info().getGoodmoney());
            }

            if (!TextUtils.isEmpty(bean.getData().getGoods_info().user_coins)) {
                tUseCoin = Integer.parseInt(bean.getData().getGoods_info().user_coins);
            }

            if (TextUtils.isDigitsOnly(bean.getData().getGoods_info().getGoodstotal().trim())) {
                total = Integer.parseInt(bean.getData().getGoods_info().getGoodstotal());
            }
            if (TextUtils.equals("hotel", bean.getData().getGoods_info().getGoods_industry())) {
                tv_hotel_hint.setText(bean.getData().getHotel_warning());
                llt_hotel_hint.setVisibility(View.VISIBLE);
            }

            et_name.setText(LoginUtils.getMember_nickname(this));
            et_phone.setText(LoginUtils.getMember_phone(this));
            updatePrice();


        }
    }


    private void updatePrice() {
        currentPrice = dPrice * count;
        if (coinCount > 0)
            currentPrice -= coinCount * 0.1;

        if (!TextUtils.equals(find_type, "goods")) {
            currentPrice = currentPrice * hotelTimeCount;
        }
        if (currentPrice <= 0)
            currentPrice = 0;

        BigDecimal bigDecimal = new BigDecimal(currentPrice);
        strPrice = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tv_price.setText("¥" + strPrice);
        tv_selector_title.setText("剩余：" + (dCoin - coinCount) + "金币，可抵扣：" + tUseCoin + "金币");

    }


    @Override
    protected void loadNetData() {

    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);

        iv_subtract.setOnClickListener(this);
        iv_add.setOnClickListener(this);
        iv_selector_add.setOnClickListener(this);
        iv_selector_subtract.setOnClickListener(this);
        applyPay_surePayTv.setOnClickListener(this);

        weixinCb.setOnCheckedChangeListener(this);
        zhifubaoCb.setOnCheckedChangeListener(this);
        yinlianCb.setOnCheckedChangeListener(this);
        yueCb.setOnCheckedChangeListener(this);

        playOrderDialog.setOnclickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(FindPayOrderActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.feedback_submit:
                //提交...
                break;
            case R.id.iv_add://数量加
                if (count == total)
                    break;
                count++;
                tv_count.setText(count + "");
                updatePrice();
                break;
            case R.id.iv_subtract://数量减
                if (count == 1)
                    break;
                count--;
                tv_count.setText(count + "");
                updatePrice();
                break;
            case R.id.iv_selector_add://金币加
                if (dCoin == coinCount)
                    break;
                if (coinCount >= tUseCoin || currentPrice == 0) {
                    ToastUtils.showToast("使用金币抵扣已上限!");
                    break;
                }
                coinCount++;
                updateCoin();
                break;
            case R.id.iv_selector_subtract://金币减
                if (coinCount == 0)
                    break;
                coinCount--;
                updateCoin();
                break;

            case R.id.applyPay_surePayTv://支付
                if (currentPrice < 0){
                    break;
                }
                pay();
                break;

            case R.id.bind_success_sure:
                Map<String, String> mapRegister = new HashMap<>();
                mapRegister.put("service", "Find_Order.orderBuy");
                mapRegister.put("token", LoginUtils.getToken(this));
                mapRegister.put("member_id", LoginUtils.getMember_id(this));
                mapRegister.put("buyer_name", et_name.getText().toString().trim());
                mapRegister.put("buyer_phone", et_phone.getText().toString().trim());
                mapRegister.put("remark", et_remark.getText().toString().trim());
                mapRegister.put("order_price", strPrice + "");
                mapRegister.put("goods_id", goods_id);
                mapRegister.put("goods_num", count + "");
                mapRegister.put("cost_coin", coinCount + "");
                mapRegister.put("pay_type", "creditpay");
                mapRegister.put("coupon_id", "0");
                mapRegister.put("order_price", "" + dPrice * count);
                mapRegister.put("cost_credit", "" + currentPrice);
                LogUtils.e("mapRegister = " + mapRegister.toString());
                CommonRequestNetData.getJsonObjectData(this, mapRegister, true, new CommonRequestNetData.JsonObjectCallBack() {
                    @Override
                    public void parseJsonObject(JSONObject jsonObject) {
                        try {
                            LogUtils.e("jsonObject = " + jsonObject.toString());
                            if (jsonObject.getString("pay_state").equals("success")) {
                                CommonH5Activity.startCommH5(FindPayOrderActivity.this, 4, jsonObject.getString("URL"), null, null, null);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                playOrderDialog.dismiss();
                break;
        }
    }

    private void pay() {
        if(weixinCb.isChecked()){
            progressBar = ProgressDialog.show(this, "", "", false, false);
            Map<String, String> mapRegister = new HashMap<>();
            mapRegister.put("service", "Find_Order.orderBuy");
            mapRegister.put("token", LoginUtils.getToken(this));
            mapRegister.put("member_id", LoginUtils.getMember_id(this));
            mapRegister.put("buyer_name", et_name.getText().toString().trim());
            mapRegister.put("buyer_phone", et_phone.getText().toString().trim());
            mapRegister.put("remark", et_remark.getText().toString().trim());
            mapRegister.put("order_price", strPrice + "");
            mapRegister.put("goods_id", goods_id);
            mapRegister.put("goods_num", count + "");
            mapRegister.put("cost_coin", coinCount + "");
            mapRegister.put("pay_type", "weixin");
            mapRegister.put("coupon_id", "0");
            mapRegister.put("order_price", "" + currentPrice);
            CommonRequestNetData.getJsonObjectData(this, true, mapRegister, new CommonRequestNetData.JsonObjectCallBack() {
                @Override
                public void parseJsonObject(JSONObject jsonObject) {
                    progressBar.dismiss();
                    try {
                        jumpUrl = jsonObject.has("URL") ? jsonObject.getString("URL") : "";
                        jumpUrl += "&client_type=user";
                        String weixin_info = jsonObject.has("weixin_info") ? jsonObject.getString("weixin_info") : "";
                        LogUtils.d("weixin_info:" + weixin_info);
                        WechatPay wechatPay = new Gson().fromJson(weixin_info, WechatPay.class);
                        payWechat(wechatPay);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            return;
        }else if (zhifubaoCb.isChecked()) {

            progressBar = ProgressDialog.show(this, "", "", false, false);
            Map<String, String> mapRegister = new HashMap<>();
            mapRegister.put("service", "Find_Order.orderBuy");
            mapRegister.put("token", LoginUtils.getToken(this));
            mapRegister.put("member_id", LoginUtils.getMember_id(this));
            mapRegister.put("buyer_name", et_name.getText().toString().trim());
            mapRegister.put("buyer_phone", et_phone.getText().toString().trim());
            mapRegister.put("remark", et_remark.getText().toString().trim());
            mapRegister.put("order_price", strPrice + "");
            mapRegister.put("goods_id", goods_id);
            mapRegister.put("goods_num", count + "");
            mapRegister.put("cost_coin", coinCount + "");
            mapRegister.put("pay_type", "alipay");
            mapRegister.put("coupon_id", "0");
            mapRegister.put("order_price", "" + currentPrice);
            CommonRequestNetData.getJsonObjectData(this, true, mapRegister, new CommonRequestNetData.JsonObjectCallBack() {
                @Override
                public void parseJsonObject(JSONObject jsonObject) {
                    try {
                        String in = jsonObject.has("pay_info") ? jsonObject.getString("pay_info") : "";
                        jumpUrl = jsonObject.has("pay_info") ? jsonObject.getString("URL") : "";
                        progressBar.dismiss();
                        zhifubaoPay(in);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return;

        }else if (yinlianCb.isChecked()) {
            playYinLian();
            return;

        }

        if (yueCb.isChecked()) {
            playOrderDialog.setTitlePrice(strPrice);
            playOrderDialog.show();

            return;

        }

        ToastUtils.showToast("暂时只支付支付宝支付，请选择支付宝支付");

    }

    /**
     * 银联支付
     */
    private void playYinLian(){
        progressBar = ProgressDialog.show(this, "", "", false, false);
        UPPayAssistEx.startPay(this, null, null, "560647841473551013201", "01");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String tn = null;
                InputStream is;
                try {
                    String url = "http://101.231.204.84:8091/sim/getacptn";
                    URL myURL = new URL(url);
                    URLConnection ucon = myURL.openConnection();
                    ucon.setConnectTimeout(120000);
                    is = ucon.getInputStream();
                    int i = -1;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    while ((i = is.read()) != -1) {
                        baos.write(i);
                    }
                    tn = baos.toString();
                    is.close();
                    baos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Message msg = new Message();
                msg.what = YINLIAN_PLAY_TN;
                msg.obj = tn;
                handler.sendMessage(msg);
            }
        }).start();
    }

    /**
     * 微信支付
     *
     * @param pay
     */
    private void payWechat(WechatPay pay) {
        PayReq req = new PayReq();
        req.appId = pay.AppID;
        req.partnerId = pay.PartnerId;
        req.prepayId = pay.PrepayId;
        req.packageValue = pay.PackageValue;
        req.nonceStr = pay.NonceStr;
        req.timeStamp = pay.TimeStamp;
        req.sign = pay.Sign;
        msgApi.registerApp(pay.AppID);
        msgApi.sendReq(req);
    }

    /**
     * 支付宝支付
     */
    private void zhifubaoPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(FindPayOrderActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    try {
                        PayResult payResult = new PayResult((String) msg.obj);
                        String resultInfo = payResult.getResult();
                        String resultStatus = payResult.getResultStatus();
                        if (TextUtils.equals(resultStatus, "9000")) {
                            //// TODO: 2017/5/13 返回加载详情
                            loadPaySuccessData();
                        } else {
                            ToastUtils.showToast(payResult.getMemo());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showToast("系统繁忙！");
                    } finally {
                        progressBar.dismiss();
                    }

                    break;

                }

                case YINLIAN_PLAY_TN:
                    if (progressBar.isShowing()) {
                        progressBar.dismiss();
                    }
                    String tn = (String)msg.obj;
                    UPPayAssistEx.startPay(FindPayOrderActivity.this, null, null, tn, "01");
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private void loadPaySuccessData() {
        progressBar.dismiss();
        ToastUtils.showToast("支付成功");
        if (!TextUtils.isEmpty(jumpUrl)) {
            Intent intent = new Intent();
            intent.putExtra("jumpUrl", jumpUrl);
            setResult(Activity.RESULT_OK, intent);
            finish();
        } else
            finish();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null) {
            return;
        }
        String msg = "";
        String str = data.getExtras().getString("pay_result");
        if (str.equalsIgnoreCase("success")) {
            if (data.hasExtra("result_data")) {
                String result = data.getExtras().getString("result_data");
                msg = "支付成功！";
            }
            msg = "支付成功！";
        } else if (str.equalsIgnoreCase("fail")) {
            msg = "支付失败！";
        } else if (str.equalsIgnoreCase("cancel")) {
            msg = "用户取消了支付";
        }
        ToastUtils.showToast(msg);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        weixinCb.setChecked(false);
        zhifubaoCb.setChecked(false);
        yinlianCb.setChecked(false);
        yueCb.setChecked(false);
        switch (buttonView.getId()) {
            case R.id.applyPay_weixinCb:
                weixinCb.setChecked(isChecked);

                break;

            case R.id.applyPay_zhifubaoCb:
                zhifubaoCb.setChecked(isChecked);

                break;

            case R.id.applyPay_yinlianCb:
                yinlianCb.setChecked(isChecked);

                break;

            case R.id.applyPay_yueCb:
                yueCb.setChecked(isChecked);

                break;

            default:

                break;

        }
    }
}
